package cn.turboinfo.fuyang.api.domain.admin.usecase.profit;

import cn.turboinfo.fuyang.api.domain.common.service.company.HousekeepingCompanyService;
import cn.turboinfo.fuyang.api.domain.common.service.profit.ProfitSharingRecordService;
import cn.turboinfo.fuyang.api.domain.common.service.profit.ProfitSharingService;
import cn.turboinfo.fuyang.api.domain.common.usecase.AbstractUseCase;
import cn.turboinfo.fuyang.api.entity.common.pojo.company.HousekeepingCompany;
import cn.turboinfo.fuyang.api.entity.common.pojo.profit.ProfitSharing;
import cn.turboinfo.fuyang.api.entity.common.pojo.profit.ProfitSharingRecord;
import lombok.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.validation.constraints.NotNull;
import javax.validation.constraints.Positive;
import java.util.List;

@Slf4j
@RequiredArgsConstructor
@Component
public class ProfitSharingViewUseCase extends AbstractUseCase<ProfitSharingViewUseCase.InputData, ProfitSharingViewUseCase.OutputData> {
    private final ProfitSharingService profitSharingService;


    private final ProfitSharingRecordService profitSharingRecordService;

    private final HousekeepingCompanyService housekeepingCompanyService;

    @Override
    protected OutputData doAction(InputData inputData) {

        Long companyId = inputData.getCompanyId();
        Long id = inputData.getId();

        ProfitSharing profitSharing = profitSharingService.getByIdEnsure(id);

        if (companyId != null && companyId > 0L) {
            if (!companyId.equals(profitSharing.getCompanyId())) {
                throw new IllegalArgumentException("分账ID与公司ID不匹配");
            }
        }

        List<ProfitSharingRecord> recordList = profitSharingRecordService.findByProfitSharingId(profitSharing.getId());

        HousekeepingCompany company = housekeepingCompanyService.getByIdEnsure(profitSharing.getCompanyId());

        profitSharing.setCompanyName(company.getName());

        return OutputData.builder()
                .profitSharing(profitSharing)
                .recordList(recordList)
                .build();
    }

    @EqualsAndHashCode(
            callSuper = true
    )
    @Data
    @NoArgsConstructor
    @AllArgsConstructor
    public static class InputData extends AbstractUseCase.InputData {

        @NotNull(message = "分账ID不能为空")
        @Positive(message = "分账ID必须为正数")
        private Long id;

        private Long companyId;

    }

    @Getter
    @Setter
    @Builder
    public static class OutputData extends AbstractUseCase.OutputData {

        private ProfitSharing profitSharing;

        private List<ProfitSharingRecord> recordList;
    }
}
